<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 2018/8/19
 * Time: 14:30
 */
namespace app\admin\controller;

use app\common\lib\Tool;
use think\Db;
use think\Request;

class Group extends Base
{
    public function index()
    {
        $data = Db::table('category')
            ->order('id asc')
            ->paginate(5);
        $page = $data->render();
        return view('demo/cate',['data'=>$data,'page'=>$page]);
    }

    public function updateGroup( Request $request){
        if($request->isPost()){
            $name = input('name');
            $id = input('id');
            $Ret = Db::table('category')->where('id',$id)->update(['name' => $name]);
            if($Ret){
                return Tool::json(1,[],'修改分类成功');
            }else{
                return Tool::json(0,[],'修改分类失败');
            }
        }else{
            $id = input('id');
            $Ret = Db::table('category')->where('id',$id)->find();
            return view('demo/admin-edit',['Ret'=>$Ret]);
        }
    }

    public function deleteGroup(){
        $id = input('id');
        $Ret = Db::table('category')->where('id',$id)->delete();
        if($Ret){
            return Tool::json(1,[],'删除分类成功');
        }else{
            return Tool::json(0,[],'删除分类失败');
        }
    }

    public function addGroup(){
        $cateName = input('cateName');
        if(empty($cateName)){
            return Tool::json(0,[],'分类名不能为空');
        }
        $RetCategory = Db::table('category')->where('name',trim($cateName))->find();
        if($RetCategory){
            return Tool::json(0,[],'分类名已存在');
        }
        $Ret = Db::name('category')->insert(['name' => $cateName]);
        if($Ret){
            return Tool::json(1,[],'添加分类成功');
        }else{
            return Tool::json(0,[],'添加分类失败');
        }
    }
}